import time
import traceback
import logging
import os

from info_config import dbname
from info_config import prometheus_url
from info_config import time_interval
from info_config import check_cnt
from info_config import prometheus_metrics_name
from info_config import con_timeout

from tool_util import push_simple_metric
from tool_util import create_conn
from tool_util import get_pg_replicat_client_addr
from tool_util import get_rds_resource_info


pg_client_addr_global = {}

# Get the current script path
script_path = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_path, "master_slave_switch.log")

logging.basicConfig(
    filename=log_file,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


def master_switch_monitor(pg_info):
    id = pg_info[0]
    name = pg_info[1]
    pg_host = pg_info[2].get("host")
    pg_port = pg_info[2].get("port")
    conn = create_conn(pg_host, pg_port, dbname, timeout=con_timeout)
    if conn is None:
        return
    current_slave_client = get_pg_replicat_client_addr(conn)
    if current_slave_client is None:
        return
    old_slave_client_info = pg_client_addr_global.get(id)
    if old_slave_client_info is None:
        pg_client_addr_global.update(
            {id: {"old_slave_client": current_slave_client, "state_cnt": 0, "state": 0}}
        )
        return
    old_slave_client = old_slave_client_info.get("old_slave_client")
    state_cnt = old_slave_client_info.get("state_cnt")
    state = old_slave_client_info.get("state")
    if current_slave_client != old_slave_client:
        pg_client_addr_global.get(id).update({"state_cnt": state_cnt + 1})
        pg_client_addr_global.get(id).update({"state": 1})
        state = 1

    if state == 1 and state_cnt >= check_cnt:
        pg_client_addr_global.get(id).update({"old_slave_client": current_slave_client})
        pg_client_addr_global.get(id).update({"state": 0})
        pg_client_addr_global.get(id).update({"state_cnt": 0})

    push_simple_metric(
        f"{prometheus_metrics_name}", state, id, name, gateway_url=prometheus_url
    )


def master_switch_monitor_all():
    pg_info_list = get_rds_resource_info()
    while True:
        for pg_info in pg_info_list:
            try:
                logging.info(f"start monitor {pg_info}")
                master_switch_monitor(pg_info)
            except Exception as e:
                traceback.print_exc()
        time.sleep(time_interval)

def main():
    master_switch_monitor_all()

if __name__ == "__main__":
    main()
